export const getMultimediaUri = (type) => {
  return '/api/backend/upload/index'
}

export const upload = ({ type = 4, file, simditor = 0, progress }) => {
  const form = new FormData()
  const xhr = new XMLHttpRequest()
  // eslint-disable-next-line promise/param-names
  return new Promise((reoslve, reject) => {
    form.append('type', type)
    form.append('simditor', simditor)
    form.append('file', file)
    xhr.withCredentials = true
    xhr.open('POST', getMultimediaUri(type), true)
    xhr.onload = (e) => {
      if (xhr.status < 200 || xhr.status >= 300) {
        reject(new Error('error'))
      } else {
        const data = JSON.parse(e.target.responseText)
        reoslve(data.data)
      }
    }
    xhr.onerror = (e) => {
      reject(e)
    }
    if (progress) {
      xhr.upload.onprogress = (e) => {
        if (e.total > 0) {
          progress((e.loaded / e.total) * 100)
        }
      }
    }
    xhr.send(form)
  })
}

export const uploadMultimedia = async (type, files, simditor, progress) => {
  const data = []
  for (let i = files.length - 1; i >= 0; i -= 1) {
    data.push(await upload({ type, file: files.item(i), simditor, progress }))
  }
  return data.reverse()
}
